package handler

import (
	"fmt"
	"net/http"

	"demo/apiservice/internal/logic"
	"demo/apiservice/internal/svc"
	"demo/apiservice/internal/types"

	"github.com/zeromicro/go-zero/rest/httpx"

	orderlogic "demo/logic"
	"demo/models"
)

func ApiserviceHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req types.Request
		if err := httpx.Parse(r, &req); err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}

		l := logic.NewApiserviceLogic(r.Context(), svcCtx)
		resp, err := l.Apiservice(&req)
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
		} else {
			httpx.OkJsonCtx(r.Context(), w, resp)
		}
	}
}

//自定义路由函数区

// create
func OrderCreateController() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		//获取请求参数
		var req models.Order
		err := httpx.ParseJsonBody(r, &req)
		if err != nil {
			//fmt.Printf("ordercontoller err:%v", err)
			httpx.WriteJson(w, 500, fmt.Sprintf("ordercontoller err:%v", err))
			return
		}
		err = orderlogic.OrderLogic.Create(req)
		if err != nil {
			//fmt.Printf("order create err:%v", err)
			httpx.WriteJson(w, 500, fmt.Sprintf("order create err:%v", err))
			return
		}
		httpx.OkJson(w, map[string]string{"code": "200", "message": "插入成功!"})

	}
}

// update
func OrderUpdateController() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req models.Order
		err := httpx.ParseJsonBody(r, &req)
		if err != nil {
			httpx.WriteJson(w, 500, fmt.Sprintf("update err:%v", err))
			return
		}
		err = orderlogic.OrderLogic.Update(req)
		if err != nil {
			//...
			return
		}
		httpx.OkJson(w, map[string]string{"code": "200", "message": "更新成功!"})

	}
}

//Remove

func OrderRemove() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req models.Order
		err := httpx.ParseJsonBody(r, &req)
		if err != nil {
			httpx.WriteJson(w, 500, fmt.Sprintf("remove err%v", err))
			return
		}
		err = orderlogic.OrderLogic.Remove(req)
		if err != nil {
			//...
			return
		}
		httpx.OkJson(w, map[string]string{"code": "200", "message": "删除成功!"})
	}
}

//List

func OrderList() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		res, err := orderlogic.OrderLogic.List()
		if err != nil {
			//...
			return
		}
		httpx.OkJson(w, res)
	}
}
